package com.xiaolei.AndPermissionKtx

import android.content.Context
import androidx.fragment.app.Fragment
import com.yanzhenjie.permission.AndPermission

/**
 * 动态请求权限
 *
 * @param permission 请求的权限
 */
inline fun <reified T : Context> T.requestPermission(
    permission: Array<String>,
    noinline onresult: ((granted: Boolean, permissions: Array<String>?) -> Unit)? = null,
    noinline onFinally: (() -> Unit)? = null,
)
{
    if (AndPermission.hasPermissions(this, *permission))
    {
        onresult?.invoke(true, permission)
        return
    }
    try
    {
        AndPermission.with(this).runtime().permission(*permission).onGranted { data ->
            try
            {
                onresult?.invoke(true, data.toTypedArray())
            } catch (e: Exception)
            {
                e.printStackTrace()
            } finally
            {
                onFinally?.invoke()
            }
        }.onDenied { data ->
            try
            {
                onresult?.invoke(false, data.toTypedArray())
            } catch (e: Exception)
            {
                e.printStackTrace()
            } finally
            {
                onFinally?.invoke()
            }
        }.start()
    } catch (e: Exception)
    {
        onresult?.invoke(false, permission)
        onFinally?.invoke()
        e.printStackTrace()
    }
}

/**
 * 检查是否已有权限
 */
inline fun <reified T : Context> T.checkPermissions(permission: Array<String>): Boolean
{
    return AndPermission.hasPermissions(this, *permission)
}

/**
 * 动态请求权限
 *
 * @param permission 请求的权限
 */
inline fun <reified T : Fragment> T.requestPermission(
    permission: Array<String>,
    noinline onresult: ((granted: Boolean, permissions: Array<String>?) -> Unit)? = null,
    noinline onFinally: (() -> Unit)? = null,
) = this.requireActivity().requestPermission(permission, onresult, onFinally)

/**
 * 检查是否已有权限
 */
inline fun <reified T : Fragment> T.checkPermissions(permission: Array<String>): Boolean
{
    return AndPermission.hasPermissions(this, *permission)
}